# Copyright 2018 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare, float_round
import logging
from odoo.exceptions import UserError,Warning

_logger = logging.getLogger(__name__)

class PurchaseOrderLine(models.Model):
    _inherit = "purchase.order.line"


    #一键同步价格，影响stock.move的unit price , value,和account move 的crdit decite
    @api.multi
    def button_einfo_sys_stock_picking_move_account(self):
        _logger.info('button_einfo_sys_stock_picking_move_account')
        stock_move = self.move_ids[0]
        # remaining_qty 
        # remaining_value 
        _logger.info('remaining_qty %s , quantity_done %s',stock_move.remaining_qty,stock_move.quantity_done)
        if(stock_move.remaining_qty == stock_move.quantity_done):
            _logger.info('purchase unit price %f, total %f',self.price_unit,self.price_total)
            _logger.info('stock_move unit price %f, total %f , ',stock_move.price_unit,stock_move.value)
            account_move = stock_move.account_move_ids[0]
            sql_query = """UPDATE stock_move SET price_unit = %s , value = %s , remaining_value = %s WHERE id = %s"""
            self.env.cr.execute(sql_query,(self.price_unit,self.price_total,self.price_total,stock_move.id))
            account_move.sudo().write({'state':'draft'})
        else :
            raise Warning(_(u'该stock.move一部分数量给使用'))
        # for aml in account_move.line_ids:
        #     if aml.debit != 0:
        #         _logger.info('debit %s',aml.debit)
        #         aml.sudo().write({'debit':self.price_total})
        #     if aml.credit != 0:
        #         _logger.info('credit %s',aml.credit)
        #         aml.sudo().write({'credit':self.price_total})
        # account_move.post()
        return

  